package com.rapida.framwork;

import java.lang.reflect.Field;
import java.util.ArrayList;

import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.rapida.app.BaseActivity;

/**
 * Created by mm on 14-12-17.
 */
public class RapidActivity extends BaseActivity implements IView {
	private PresenterImpl mPresenrerImpl;

	public void registerViewEvent(BaseActivity activity) {
        if (mPresenrerImpl != null) {
            registerViewEvent(mPresenrerImpl.getViews(), activity.getWindow().getDecorView());
        }
	}

	public void registerViewEvent(ArrayList<Object> classObjs, View rootView) {
		for (Object obj : classObjs) {
			registerViewEvent(obj, rootView);
		}
	}

	private void registerViewEvent(Object classObj, View rootView) {
		Field[] fields = classObj.getClass().getDeclaredFields();
		if (fields != null && fields.length > 0) {
			for (Field field : fields) {
				try {
					field.setAccessible(true);
					if (field.get(classObj) != null) {
						continue;
					}
					ViewRegister viewreg = field.getAnnotation(ViewRegister.class);
					int viewId = viewreg.id();
					field.set(classObj, rootView.findViewById(viewId));
					Object obj = field.get(classObj);
					if (viewreg.click()) {
						if (obj instanceof View) {
							((View) obj).setOnClickListener(this);
						}
					}
					if (viewreg.longClick()) {
						if (obj instanceof View) {
							((View) obj).setOnLongClickListener(this);
						}
					}
					if (viewreg.itemClick()) {
						if (obj instanceof ListView) {
							((ListView) obj).setOnItemClickListener(this);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public boolean onLongClick(View v) {
		if (mPresenrerImpl == null) {
			return false;
		}
		return mPresenrerImpl.onLongClick(v);
	}

	@Override
	public void onClick(View v) {
		if (mPresenrerImpl != null) {
			mPresenrerImpl.onClick(v);
		}
	}

	public void setPresenter(PresenterImpl impl) {
		mPresenrerImpl = impl;
		registerViewEvent(this);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (mPresenrerImpl != null) {
			mPresenrerImpl.onItemClick(arg0, arg1, arg2, arg3);
		}
	}
}
